package com.lmx.persistence.service;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lmx.common.constants.ICommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.GenerateQrCodeUtil;
import com.lmx.common.util.HttpRequestUtil;
import com.lmx.common.util.PropertiesFileUtil;
import com.lmx.common.util.XMLUtil;
import com.lmx.repoDomain.tmodel.Account;
import com.lmx.repoDomain.tmodel.DealFlow;
import com.lmx.repoDomain.tmodel.PayRecord;
import com.lmx.repoDomain.tmodel.Task;
import com.lmx.repoDomain.tmodel.UserTask;
import com.lmx.repoDomain.tmodel.Wechat;
import com.lmx.repoDomain.tmodel.Workorder;
//import com.lmx.repoDomain.model.*;
import com.lmx.repoDomain.tmodel.business.User;//huibati

import net.sf.json.JSONObject;

/**
 * Created by qin on 2016/8/11.
 */
@Service
public class PayRecordService {
    private Log logger = LogFactory.getLog(this.getClass());
    @PersistenceContext
    private EntityManager em;
    @Autowired
    private MessageService messageService;
    @Autowired
    private GenericService dslJpaService;
    @Autowired
    private CommonService commonService;

    /**
     * 提现
     * @param payRecord
     * @return
     */
    public PayRecord Withdraw(PayRecord payRecord){
        Double amount = payRecord.getAmount();//提现金额
        String failReason = "";

        if (!checkWeek()){
            failReason = "每周的周一、周二才能提现";
            payRecord.setErrcode(ICommonConstants.INTERFACEERRO.OTHERFAIL.ordinal());
            payRecord.setFailReason(failReason);
            logger.debug(failReason);
            return payRecord;
        }

        Double balance = (Double)this.em.createQuery("select a.balance from Account a where a.user.id = ?1")
                .setParameter(1,payRecord.getUser().getId())
                .getSingleResult();
        if(balance == null || balance < amount){
            failReason = "您的提现金额超出了账户的余额，请重新输入";
            payRecord.setErrcode(ICommonConstants.INTERFACEERRO.OTHERFAIL.ordinal());
            payRecord.setFailReason(failReason);
            logger.debug(failReason);
            return payRecord;
        }

        long num = (Long)this.em.createQuery("select count(p.id) from  PayRecord p where p.user.id = ?1 and p.createTime > ?2")
                .setParameter(1,payRecord.getUser().getId())
                .setParameter(2, CommonUtil.getDayBegin())
                .getSingleResult();
        int allowWithdrawNum = commonService.getAllowWithdrawNum();
        if(num >= allowWithdrawNum){
            failReason = "每天的提现次数不能大于" + allowWithdrawNum +"次";
            payRecord.setErrcode(ICommonConstants.INTERFACEERRO.OTHERFAIL.ordinal());
            payRecord.setFailReason(failReason);
            logger.debug(failReason);
            return payRecord;
        }
        logger.debug("验证通过，创建提现申请");

        double proportion = commonService.getProportion();//提佣比例
        payRecord.setPlatformProportion(proportion);
        payRecord.setAmount(amount * ( 1 - proportion)); //设置支付金额

        dslJpaService.setEntityClass(PayRecord.class);
        payRecord = (PayRecord)dslJpaService.create(payRecord);

        //创建交易流水记录
        DealFlow dealFlow = new DealFlow();
        dealFlow.setPayer(payRecord.getUser());
        Account payerAccount = (Account)this.em.createQuery("select a from Account a where a.user.id = ?1")
                .setParameter(1,payRecord.getUser().getId())
                .getSingleResult();
        double payerBalance = payerAccount.getBalance() - amount;
        dslJpaService.setEntityClass(Account.class);
        payerAccount.setBalance(payerBalance);
        dslJpaService.update(payerAccount);
        dealFlow.setPayerBalance(payerBalance);
        dealFlow.setPayee(commonService.getSystemUser());
        dealFlow.setAmount(amount);
        dealFlow.setBusinessType(ActionContextHolder.getDicctypeHolder().get("bizTypeWithdrawCash"));
        dealFlow.setPayRecord(payRecord);
        int currTime = CommonUtil.getCurrTimes();
        dealFlow.setCreateTime(currTime);
        dealFlow.setTradeTime(currTime);
        dslJpaService.setEntityClass(DealFlow.class);
        dslJpaService.create(dealFlow);

        logger.debug("创建提现申请成功");
        String content = "客服：" + payRecord.getUser().getName()
                + "<br>loginName：" + payRecord.getUser().getLoginName()
                + "<br>申请提现"
                + "<br>" + "申请时间：" + CommonUtil.getCurrTimeForString();
        commonService.operateRemind("用户提现申请",content);
        return payRecord;
    }

    /**
     * 检查当前week是否可提现
     * @return
     */
    public boolean checkWeek(){
        Date date = new Date();
        boolean flag = false;
        String[] weeks = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if(week_index<0){
            week_index = 0;
        }
        logger.debug("提现审核 当前："+ weeks[week_index]);
        ArrayList<Integer> week = commonService.getWeek();
        for (int i = 0; i < week.size(); i++) {
            if(week_index == week.get(i)){
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 扫码支付  充值
     */
    public  PayRecord recharge(PayRecord payRecord) {
        logger.debug("pay 进入扫码重启");
        dslJpaService.setEntityClass(PayRecord.class);
        payRecord = (PayRecord)dslJpaService.create(payRecord);
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String appid = properties.getProperty("weixin.appid");
        String mch_id = properties.getProperty("weixin.mch_id");
        String device_info = properties.getProperty("weixin.device_info");
        String key = properties.getProperty("weixin.key");
        String unifiedorderURL = properties.getProperty("weixin.url.unifiedorder");
        String notify_url = properties.getProperty("weixin.notify_url");//回调地址
        String nonce_str = CommonUtil.createNonceStr(); //随机字符串
        String body = "呼叫云充值";//商品描述
        String totalFee = (int)(payRecord.getAmount() * 100) + ""; //金额必须为整数  单位为分
        String productId = payRecord.getId().toString(); // 商户根据自己业务传递的参数 必填
        String tradeNo = CommonUtil.getOrderNo();//商户 后台的贸易单号
        logger.debug("payment nonce_str: " + nonce_str);
        logger.debug("payment productId: " + productId);
        logger.debug("payment tradeNo: " + tradeNo);

        SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
        parameters.put("appid", appid);
        parameters.put("mch_id", mch_id);
        parameters.put("device_info", device_info);
        parameters.put("body", body);
        parameters.put("nonce_str", nonce_str);
        parameters.put("trade_type", "NATIVE"); //交易类型
        parameters.put("spbill_create_ip", localIp()); //本机的Ip
        parameters.put("product_id", productId); // 商户根据自己业务传递的参数 必填
        parameters.put("out_trade_no", tradeNo); //商户 后台的贸易单号
        parameters.put("total_fee", totalFee); //金额必须为整数  单位为分
        parameters.put("notify_url", notify_url); //支付成功后，回调地址
        parameters.put("sign", createSign(key, parameters));
        String xmlData = XMLUtil.converter(parameters);
        logger.debug(xmlData);
        String resXml = HttpRequestUtil.postData(unifiedorderURL, xmlData);
        logger.debug(resXml);
        Document dd = null;
        String code_url = null;
        try {
            dd = DocumentHelper.parseText(resXml);
        } catch (DocumentException e) {
            logger.debug(e.toString());
        }
        if (dd != null) {
            Element root = dd.getRootElement();
            if (root == null) {
                return null;
            }
            Element codeUrl = root.element("code_url");
            if (codeUrl == null) {
                return null;
            }
            code_url = codeUrl.getText();  //解析 xml 获得 code_url
        }
        logger.debug(code_url);
        payRecord.setCode(tradeNo);
        payRecord.setPayStatus((short) ICommonConstants.PAYSTATUS.NOPAY.ordinal());
        payRecord.setPayType((short)ICommonConstants.PAYTYPE.RECHARGE.ordinal());
        String relativePath = GenerateQrCodeUtil.generateQrcode(code_url);
        payRecord.setWechatQrPay(relativePath);
        payRecord.setPayChannel((short)ICommonConstants.PAYCHANNEL.WEIXIN.ordinal());
        dslJpaService.setEntityClass(PayRecord.class);
        payRecord = (PayRecord)dslJpaService.update(payRecord);
        logger.debug("pay 生成扫码支付二维码");
        return payRecord;
    }


    /**
     * 获取本机Ip
     *
     *  通过 获取系统所有的networkInterface网络接口 然后遍历 每个网络下的InterfaceAddress组。
     *  获得符合 <code>InetAddress instanceof Inet4Address</code> 条件的一个IpV4地址
     * @return
     */
    private String localIp(){
        String ip = null;
        Enumeration allNetInterfaces;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
                for (InterfaceAddress add : InterfaceAddress) {
                    InetAddress Ip = add.getAddress();
                    if (Ip != null && Ip instanceof Inet4Address) {
                        ip = Ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            logger.warn("获取本机Ip失败:异常信息:"+e.getMessage());
        }
        return ip;
    }

    /**
     * 微信支付签名算法sign
     * @param parameters
     * @return
     */
    public static String createSign(String key,SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
//        key = "192006250b4c09247ec02edce69f6a2d";//debugTest
        sb.append("key=" + key);
        System.out.println(sb);
        String sign = CommonUtil.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
        return sign;
    }


    /**
     * 充值确认处理
     */
    public boolean rechargeAffirm(Map map){
        boolean flag = false;
   
        return flag;
    }


    /**
     * xml转换为有序map
     * @param resXml
     * @return
     */
    public SortedMap XmlToSortedMap(String resXml){
        Document dd = null;
        SortedMap<Object, Object> map = new TreeMap<Object, Object>();
        try {
            dd = DocumentHelper.parseText(resXml);
        } catch (DocumentException e) {
            logger.debug(e.toString());
        }
        if (dd != null) {
            Element root = dd.getRootElement();
            if (root == null) {
                return null;
            }
            List<Element> list= root.elements();
            for (int i = 0; i < list.size(); i++) {
                logger.debug(list.get(i).getName() + ":" + list.get(i).getText());
                map.put(list.get(i).getName(),list.get(i).getText());
            }
        }
        return map;
    }


    /**
     * 签名验证
     * @return
     */
    public boolean verifySign(SortedMap map){
        boolean flag = false;
        String sign = map.get("sign").toString();
        map.remove("sign");
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String key = properties.getProperty("weixin.key");
        String signVerify = createSign(key,map);
        if(StringUtils.isNotBlank(sign) && sign.equals(signVerify)){
            flag = true;
        }
        return flag;
    }

    /**
     * 生成绑定微信二维码
     * @return
     */
    public Wechat bindQr(Wechat wechat){
        if(wechat.getUser() != null && wechat.getUser().getId() != ActionContextHolder.getContext().getUser().getId()){
            wechat.setErrcode(ICommonConstants.INTERFACEERRO.OTHERFAIL.ordinal());
            return wechat;
        }
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String appid = properties.getProperty("weixin.appid");
        String authorizeURL = properties.getProperty("weixin.url.authorize");
        String redirectURL = properties.getProperty("weixin.url.redirect");
        String state = ActionContextHolder.getContext().getUser().getId().toString();
        String content = authorizeURL + "?appid=" + appid + "&&redirect_uri=" + CommonUtil.URLEncoding(redirectURL) + "&response_type=code&scope=snsapi_userinfo&state=" + state + "#wechat_redirect";
        String relativePath = GenerateQrCodeUtil.generateQrcode(content);
        wechat.setQrUrl(relativePath);
        wechat.setUser(ActionContextHolder.getContext().getUser());
        wechat.setBindStatus((short)ICommonConstants.BINDSTATUS.FALSE.ordinal());
        dslJpaService.setEntityClass(Wechat.class);
        if(wechat.getId() == null){
            List list = this.em.createQuery("select w from Wechat w where w.user.id = ?1")
                    .setParameter(1,wechat.getUser().getId())
                    .getResultList();
            if(list.size() > 0){
                return null;
            }
            wechat = (Wechat)dslJpaService.create(wechat);
        }else {
            wechat = (Wechat)dslJpaService.update(wechat);
        }
        logger.debug("Wechat 生成绑定二维码");
        return wechat;
    }

    /**
     * 微信回调绑定 wechat
     */
    public Wechat bindWechat(String code , String state){
        Long userId = Long.parseLong(state);
        List list = this.em.createQuery("select w from Wechat w where w.user.id = ?1")
                .setParameter(1,userId)
                .getResultList();
        if(list.size() <= 0){
            return null;
        }
        Wechat  wechat = (Wechat)list.get(0);
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String appid = properties.getProperty("weixin.appid");
        String appsecret = properties.getProperty("weixin.appsecret");
        String accessURL = properties.getProperty("weixin.url.access");
        String userinfoURL = properties.getProperty("weixin.url.userinfo");
        String res = HttpRequestUtil.httpsGet(accessURL + "?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code");
        logger.debug("bind res :" +res);
        Document dd = null;
        JSONObject resJson = JSONObject.fromObject(res);
        String openid = resJson.getString("openid");
        String access_token=resJson.getString("access_token");
        logger.debug("bind access_token:" + access_token);
        logger.debug("bind openid:" + openid);
        if (StringUtils.isNotBlank(access_token) && StringUtils.isNotBlank(openid)){
            logger.debug("-----------------------------bind--------------------------------");
            res = HttpRequestUtil.httpsGet(userinfoURL + "?access_token="+access_token+"&openid="+openid+"&lang=zh_CN");
            logger.debug("bind res :" +res);
            resJson = JSONObject.fromObject(res);
            String nickname = resJson.getString("nickname");
            String sex =  resJson.getString("sex");
            String language =  resJson.getString("language");
            String city =  resJson.getString("city");
            String province =  resJson.getString("province");
            String country =  resJson.getString("country");
            String headimgurl =  resJson.getString("headimgurl");
            wechat.setOpenid(openid);
            wechat.setNickname(nickname);
            wechat.setSex(Short.parseShort(sex));
            wechat.setLanguage(language);
            wechat.setCity(city);
            wechat.setProvince(province);
            wechat.setCountry(country);
            logger.debug("headimgurl:" + headimgurl);
            logger.debug("headimgurl" + headimgurl.replace("\\",""));
            wechat.setHeadimgurl(headimgurl.replace("\\",""));
            wechat.setBindStatus((short)ICommonConstants.BINDSTATUS.TRUE.ordinal());
            dslJpaService.setEntityClass(Wechat.class);
            wechat = (Wechat)dslJpaService.update(wechat);

        }
        messageService.wechatBindRemind(wechat);
        return  wechat;
    }

    /**
     * 提现（企业打款）
     */
    public  boolean transfers(PayRecord payRecord){
        boolean flag = false;
        payRecord = this.em.find(PayRecord.class,payRecord.getId());
        if(StringUtils.isNotBlank(payRecord.getCode()) && payRecord.getCode().length() > 0){
            logger.debug("提现请求重复");
            return flag;
        }
        Properties properties = PropertiesFileUtil.getApplicationProperties();
        String appid = properties.getProperty("weixin.appid");
        String mch_id = properties.getProperty("weixin.mch_id");
        String key = properties.getProperty("weixin.key");
        String transfersUrl = properties.getProperty("weixin.url.transfers");
        String nonce_str = CommonUtil.createNonceStr(); //随机字符串
//        String partner_trade_no = payRecord.getId().toString();//商户订单号
        String partner_trade_no = CommonUtil.getOrderNo();//商户订单号
        payRecord.setCode(partner_trade_no);
        dslJpaService.setEntityClass(PayRecord.class);
        dslJpaService.update(payRecord);
        List list = this.em.createQuery("select w from Wechat w where w.user.id = ?1")
                .setParameter(1,payRecord.getUser().getId())
                .getResultList();
        if(list.size() <= 0){
            return flag;
        }
        Wechat  wechat = (Wechat)list.get(0);
        String openid = wechat.getOpenid();
        String amount = (int)(payRecord.getAmount() * 100) + "";

        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
        parameters.put("mch_appid", appid);
        parameters.put("mchid", mch_id);
        parameters.put("partner_trade_no", partner_trade_no); //商户订单号
        parameters.put("openid", openid);
        parameters.put("nonce_str", nonce_str);
        parameters.put("check_name", "NO_CHECK");
//        parameters.put("re_user_name", "3213");
        parameters.put("amount", amount);//金额必须为整数  单位为分
        parameters.put("desc", "提现");
        parameters.put("spbill_create_ip",localIp()); //本机的Ip

        parameters.put("sign",createSign(key,parameters));
        String xmlData = XMLUtil.converter(parameters) ;
        logger.debug("weixin XML 请求：" + xmlData);

        String resXml = HttpRequestUtil.postDataSSL(transfersUrl, xmlData);
        logger.debug("weixin resXML : " + resXml);

        Document dd = null;
        String resCode=null;
        try {
            dd = DocumentHelper.parseText(resXml);
        } catch (DocumentException e) {
            logger.debug(e.toString());
        }
        if (dd != null) {
            Element root = dd.getRootElement();
            if (root == null) {
                return flag;
            }
            Element result = root.element("return_code");
            if (result == null) {
                return flag;
            }
            resCode = result.getText();  //解析 xml 获得 resCode
        }
        logger.debug("resCode:" + resCode);
        if("SUCCESS".equals(resCode)){
            logger.debug("恭喜您提现成功！！！");
            flag = true;
            User user = this.em.find(User.class,payRecord.getUser().getId());
            if(user.getInviteUser() != null){
                Double commission =  payRecord.getAmount() * commonService.getInvitationCommissionProp();
                Account inviterAccount = (Account)this.em.createQuery("select a from Account a where a.user.id = ?1")
                        .setParameter(1,payRecord.getUser().getInviteUser().getId())
                        .getSingleResult();
                Account sysOutAccount = commonService.getSysOutAccount();
                inviterAccount.setBalance(inviterAccount.getBalance() + commission);
                sysOutAccount.setBalance(sysOutAccount.getBalance() - commission);
                dslJpaService.setEntityClass(Account.class);
                dslJpaService.update(inviterAccount);
                dslJpaService.update(sysOutAccount);
                DealFlow dealFlow = new DealFlow();
                dealFlow.setAmount(commission);
                dealFlow.setBusinessType(ActionContextHolder.getDicctypeHolder().get("bizTypeCsInviteCodeCommission"));
                dealFlow.setPayee(user.getInviteUser());
                dealFlow.setPayer(sysOutAccount.getUser());
                dealFlow.setTradeTime(CommonUtil.getCurrTimes());
//        dealFlow.setInitiator();//debugTest
                dealFlow.setPayeeBalance(inviterAccount.getBalance());
                dealFlow.setPayerBalance(sysOutAccount.getBalance());
                dslJpaService.setEntityClass(DealFlow.class);
                dslJpaService.create(dealFlow);
                logger.debug("提现划拨邀请提佣成功！");
            }

        }
        return flag;
    }

    /**
     * 确认成单-费用划拨
     */
    public void confirmOrder(Workorder workorder){

        User user = this.em.find(User.class,workorder.getCreater().getId());
        Task task = this.em.find(Task.class,workorder.getTask().getId());
        Double fee = task.getPoPay();//debugTest
        if(fee == null || fee == 0){
            logger.debug("无成单费用，成单费用划拨终止");
            return;
        }

        List list = this.em.createQuery("select a from Account a where a.user.id = ?1")
                .setParameter(1,user.getId())
                .getResultList();
        if(list.size() != 1){
            logger.debug("客服账户异常，成单费用划拨终止");
            return;
        }
        Account userAccount = (Account)list.get(0);
        list = this.em.createQuery("select a from Account a where a.user.id = ?1")
                .setParameter(1,task.getPubuser().getId())
                .getResultList();
        if(list.size() != 1){
            logger.debug("企业账户异常，成单费用划拨终止");
            return;
        }
        Account entAccount =  (Account)list.get(0);

        userAccount.setBalance(userAccount.getBalance() + fee);
        entAccount.setBalance(entAccount.getBalance() - fee);
        dslJpaService.setEntityClass(Account.class);
        dslJpaService.update(userAccount);
        dslJpaService.update(entAccount);

        DealFlow dealFlow = new DealFlow();
        dealFlow.setAmount(fee);
        dealFlow.setBusinessType(ActionContextHolder.getDicctypeHolder().get("bizTypeCsMakeADeal"));
        dealFlow.setPayee(user);
        dealFlow.setPayer(task.getPubuser());
        dealFlow.setTradeTime(CommonUtil.getCurrTimes());
        dealFlow.setTask(task);
//        dealFlow.setInitiator();//debugTest
        dealFlow.setPayeeBalance(userAccount.getBalance());
        dealFlow.setPayerBalance(entAccount.getBalance());
        dslJpaService.setEntityClass(DealFlow.class);
        dslJpaService.create(dealFlow);
        logger.debug("客服获取成单费用成功！");


        double commission = fee * commonService.getOrderCommissionProp();
        userAccount.setBalance(userAccount.getBalance() - commission);
        Account sysInAccount = commonService.getSysInAccount();
        sysInAccount.setBalance(sysInAccount.getBalance() + commission );
        dslJpaService.setEntityClass(Account.class);
        dslJpaService.update(userAccount);
        dslJpaService.update(sysInAccount);
        dealFlow = new DealFlow();
        dealFlow.setAmount(commission);
        dealFlow.setBusinessType(ActionContextHolder.getDicctypeHolder().get("bizTypeOrderCommission"));//debugTest
        dealFlow.setPayee(sysInAccount.getUser());
        dealFlow.setPayer(user);
        dealFlow.setTradeTime(CommonUtil.getCurrTimes() + 1);
        dealFlow.setTask(task);
//        dealFlow.setInitiator();//debugTest
        dealFlow.setPayeeBalance(sysInAccount.getBalance());
        dealFlow.setPayerBalance(userAccount.getBalance());
        int prop = (int)(commonService.getOrderCommissionProp()*100);
        dealFlow.setRemark("系统提佣比例：" +  prop + "%");
        dslJpaService.setEntityClass(DealFlow.class);
        dslJpaService.create(dealFlow);
        logger.debug("平台成单提佣成功！");

        UserTask userTask = (UserTask)this.em.createQuery("select u from UserTask u where u.user.id = ?1 and u.task.id = ?2")
                .setParameter(1,user.getId())
                .setParameter(2,task.getId())
                .getSingleResult();
        userTask.setBrokerage(fee -commission);
        if(task.getSettleAccountWay() == ICommonConstants.SETTLEACCOUNTWAY.AFTERTIME.ordinal()){
            userTask.setIsSettleAccount((short)ICommonConstants.BOOLEAN.FALSE.ordinal());
            userAccount.setFreezingAmount(userAccount.getFreezingAmount() + userTask.getBrokerage());
            dslJpaService.setEntityClass(Account.class);
            dslJpaService.update(userAccount);
        }else {
            userTask.setIsSettleAccount((short)ICommonConstants.BOOLEAN.TRUE.ordinal());
        }
        dslJpaService.setEntityClass(UserTask.class);
        dslJpaService.update(userTask);
        logger.debug("成单费用划拨完成！");


    }



}

